import json
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from django.http import HttpResponse, JsonResponse
import logging
logger = logging.getLogger('django')
import random
from celery_tasks.sms.tasks import ccp_send_sms_code


# 图形验证码
class ImageCodeView(View):

    def get(self, request):
        """获取图形验证码"""
        cur = request.GET.get('cur')

        text, image = captcha.generate_captcha()
        print(text)
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % cur, 300, text)

        return HttpResponse(image,
                            content_type='image/jpg')


# 短信验证码
class SMSCodeView(View):
    """短信验证码"""

    def post(self, request):
        json_dict = json.loads(request.body)
        id = json_dict.get('id')
        mobile = json_dict.get('mobile')
        image_code_client = json_dict.get('text')

        redis_conn = get_redis_connection('verify_code')

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 400,
                                 'errmsg': '发送短信过于频繁'})

        # image_code_client = request.GET.get('image_code')
        # uuid = request.GET.get('image_code_id')

        # 2. 校验参数
        if not all([image_code_client, id]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})
        redis_conn = get_redis_connection('verify_code')
        # 4. 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return JsonResponse({'code': 400,
                                 'errmsg': '图形验证码失效'})
        # 5. 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({"errno": 4004,
                                 'errmsg': '输入图形验证码有误'})
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        # 创建redis管道
        pl = redis_conn.pipeline()
        # 保存短信验证码
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # 我们给写入的数据设置为60s,如果过期,则会获取不到.
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()

        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)
        # 10. 响应结果
        return JsonResponse({"errno": 0,
                             'errmsg': '发送短信成功'})


